<?php

namespace Portal\Controller;

use Think\Controller;

/**
 * 微信支付
 */
class WxPayController extends Controller {
	/**
	 * 初始化
	 */
	private $wxpayConfig;
	private $wxpay;
    private $PayMode ;  //支付模式
    private $OrderID;   //业务工单号
    private $totalfee;   //金额
    private $Attach;    //任务描述
	public function _initialize() {
		header ( "Content-type: text/html; charset=utf-8" );
		vendor ( 'WxPay.WxPayConf' );
		vendor ( 'WxPay.WxQrcodePay' );

		$this->wxpayConfig = C ('WxPayConf');
		$m = D ("Pay");
	 	$this->wxpay = $m->getPayPram ( "weixin" );  //取微信支付系统参数信息
		$this->wxpayConfig ['appid'] = $this->wxpay ['appId']; // 微信公众号身份的唯一标识
		$this->wxpayConfig ['appsecret'] = $this->wxpay ['appsecret']; // JSAPI接口中获取openid
		$this->wxpayConfig ['mchid'] = $this->wxpay ['mchId']; // 受理商ID
		$this->wxpayConfig ['key'] = $this->wxpay ['apiKey']; // 商户支付密钥Key
		$this->wxpayConfig ['notifyurl'] = $this->wxpay ['notifyurl'];
	//	$this->wxpayConfig ['returnurl'] = "";

		// 初始化WxPayConf_pub
		$wxpaypubconfig = new \WxPayConf ( $this->wxpayConfig );
         $this->OrderID = I('OrderID',date('ymdhis'));
         $this->totalfee = I('totalfee');
         $this->Body = I('Body','有乎儿活动支付','op_t');


         $this->_top_menu_list = array (
			'center' => array (
			'title' => '有乎儿'
		));
      $this->assign('top_menu_list', $this->_top_menu_list);
    //	print_r($this->wxpayConfig);

	}

	public function createQrcode() {
		$pkey = base64_decode ( I ( "pkey" ) );
		$pkeys = explode ( "@", $pkey );
		$pflag = true;
		if (count ( $pkeys ) != 2) {
			$this->assign ( 'out_trade_no', "" );
		} else {
			$morders = D ( 'Home/Orders' );
			$obj ["orderIds"] = $pkeys [1];
			$data = $morders->getPayOrders ( $obj );
			$orders = $data ["orders"];
			$needPay = $data ["needPay"];
			if($needPay>0){

				$this->assign ( "orders", $orders );
				$this->assign ( "needPay", $needPay );
				$this->assign ( "orderCnt", count ( $orders ) );

				// 使用统一支付接口
				$wxQrcodePay = new \WxQrcodePay ();
				$wxQrcodePay->setParameter ( "body", "支付订单費用" ); // 商品描述
				$timeStamp = time ();
				$out_trade_no = "$timeStamp";
				//$out_trade_no = "1000001|1000002";
				$wxQrcodePay->setParameter ( "out_trade_no", "$out_trade_no" ); // 商户订单号
				$wxQrcodePay->setParameter ( "total_fee", $needPay * 100 ); // 总金额
				$wxQrcodePay->setParameter ( "notify_url", C ( 'WxPayConf.NOTIFY_URL' ) ); // 通知地址
				$wxQrcodePay->setParameter ( "trade_type", "NATIVE" ); // 交易类型
				$wxQrcodePay->setParameter ( "attach", "$pkey" ); // 附加数据
				//$wxQrcodePay->setParameter ( "detail", "" );//附加数据
				$wxQrcodePay->SetParameter ( "input_charset", "UTF-8" );
				// 获取统一支付接口结果
				$wxQrcodePayResult = $wxQrcodePay->getResult ();


				// 商户根据实际情况设置相应的处理流程
				if ($wxQrcodePayResult ["return_code"] == "FAIL") {
					// 商户自行增加处理流程
					echo "通信出错：" . $wxQrcodePayResult ['return_msg'] . "<br>";
				} elseif ($wxQrcodePayResult ["result_code"] == "FAIL") {
					// 商户自行增加处理流程
					echo "错误代码：" . $wxQrcodePayResult ['err_code'] . "<br>";
					echo "错误代码描述：" . $wxQrcodePayResult ['err_code_des'] . "<br>";
				} elseif ($wxQrcodePayResult ["code_url"] != NULL) {
					// 从统一支付接口获取到code_url

					$code_url = $wxQrcodePayResult ["code_url"];
					// 商户自行增加处理流程
				}

				$this->assign ( 'out_trade_no', $obj ["orderIds"] );
				$this->assign ( 'code_url', $code_url );
				$this->assign ( 'wxQrcodePayResult', $wxQrcodePayResult );
			}else{
				$pflag = false;
			}
		}
		if($pflag){
			//$this->display ( "default/payment/wxpay/qrcode" );
			print_r('pay is falt');
		}else{
			//$this->display ( "default/payment/pay_success" );
			print_r('pay is success');
		}

	}

	public function Wxnotify() {
	 $Notify = D("Notify");  //实例化模型

		// 使用通用通知接口
		$wxQrcodePay = new \WxQrcodePay();
		// 存储微信的回调
		$xml = $GLOBALS ['HTTP_RAW_POST_DATA'];
		$wxQrcodePay->saveData ( $xml );
	  //print_r($wxQrcodePay);

		// 验证签名，并回应微信。
		if ($wxQrcodePay->checkSign () == FALSE) {

          $Notify->recordXml(0,"签名失败");   //记录错误
			$wxQrcodePay->setReturnParameter ( "return_code", "FAIL" ); // 返回状态码
			$wxQrcodePay->setReturnParameter ( "return_msg", "签名失败" ); // 返回信息

		} else {
            $Notify->recordXml(1,"验证成功");   //记录错误
			$wxQrcodePay->setReturnParameter ( "return_code", "SUCCESS" ); // 设置返回码

		}
		$returnXml = $wxQrcodePay->returnXml ();
		// ==商户根据实际情况设置相应的处理流程，此处仅作举例=======
		if ($wxQrcodePay->checkSign () == TRUE) {
			$wxXml = $wxQrcodePay->getData ();  //先将xml中数据取出来
			if ($wxQrcodePay->data ["return_code"] == "FAIL") {

			 $obj['orderid']=$wxXml['out_trade_no'];  //取订单流水号
			 $obj['OutSideId']=$wxXml['transaction_id']; //取微信支付流水号
			 $order = D("Mob/orders");
			 $order->failOrder($obj);
			  echo "FAIL";
			} elseif ($wxQrcodePay->data ["result_code"] == "FAIL") {
				// 此处应该更新一下订单状态，商户自行增删操作
			 $obj['orderid']=$wxXml['out_trade_no'];  //取订单流水号
			 $obj['OutSideId']=$wxXml['transaction_id']; //取微信支付流水号
			 $order = D("Mob/orders");
			 $order->failOrder($obj);
			   echo "FAIL";
			} elseif($wxQrcodePay->data ["result_code"] == "SUCCESS" ) {
				// 此处应该更新一下订单状态，商户自行增删操作

			   $order = D("Mob/Orders");   //先实例化order模型
			   $obj['orderid']=$wxXml['out_trade_no'];  //取订单流水号
			   $obj['OutSideId']=$wxXml['transaction_id']; //取微信支付流水号
               $obj['totalfee']=$wxXml['total_fee']; //取微信支付金额


               $CheckFlg = $order->verifyOrder($obj);   //验证结果

               if($CheckFlg)
               {

               $result = $order->CompleteOrder($obj);


               if($result)
               {


               $this->PayComplete($obj['orderid']);
             	echo "SUCCESS";
            //  echo M()->getLastSql();
               }else
               {

              	echo "SUCCESS2";
              // 	print_r($obj['orderid']);
           //echo M()->getLastSql();
               }

			}
			else   //验证失败，实际支付金额可能与订单中不符。
			{
			$order->payException($obj['orderid'],101,D("Xml")->getXml());
			//print_r($wxXml);
			echo "SUCCESS3";

			//echo M()->getLastSql();
			}
			}else
			{
          	echo "SUCCESS4";

			}
		}
	}

	/**
	 * 检查支付结果
	 */
	public function getPayStatus() {
		$trade_no = I ( 'trade_no' );
		$total_fee = S ( $trade_no );
		$data = array("status"=>-1);
		if(empty ( $total_fee )){
			$data["status"] = -1;
		}else{// 检查缓存是否存在，存在说明支付成功
			S ( $trade_no, null );
			$data["status"] = 1;
		}
		$this->ajaxReturn($data);
	}

	/**
	 * 检查支付结果
	 */
	public function paySuccess() {
		$this->display ( "default/payment/pay_success" );
	}

	public function WxQrcode()
	{
	vendor('WxPay.WxPayJsApiPay');

       $Attach = I('Attach',null);
       $ReturnUrl= I('ReturnUrl');

	   $Total_fee= $this->totalfee;
	 //  print_r($Total_fee);
       $Out_trade_no = $this->OrderID;
       $Notify_url = $this->wxpayConfig ['notifyurl'];
    // print_r($this->wxpayConfig ['notifyurl']);

   //   $url = U();

   //  print_r("Url:".$url."<br>");
   //  $enurl = urlencode($url);
    //  print_r("enUrl:".$enurl."<br>");
    //  print_r("deUrl:".urldecode($enurl)."<br>");

	    $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();

        //2、统一下单
       $input = new \WxPayUnifiedOrder();
        $input->SetBody($this->Body);
        $input->SetAttach($Attach);
        $input->SetOut_trade_no($Out_trade_no);
        $input->SetTotal_fee($Total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($Notify_url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
       //print_r($input);
       // print_r($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->jsApiParameters=$jsApiParameters;
        $this->assign('ReturnUrl',$ReturnUrl);
        $this->assign('Total_fee',number_format($Total_fee/100,2));  //由分转到元
        $this->assign('Body',$Body);
        $this->assign('Attach',$Attach);

        $this->display();

	}

     /**
	 * 支付完成操作
	 */

	private function PayComplete($OrderId)
	{

	$Order = D("Mob/orders");  //实例化模型
    $OrderInfo = $Order->queryOrder($OrderId);   //查询任务信息



    if(!$OrderInfo)  //如果查询出来的任务信息为空的话，直接返回
    {
    return ;
    }

    $OrderType = $OrderInfo['OrderType'];  //取任务订单类型
    $Serialno = $OrderInfo["businessId"]; //取任务流水号

    switch($OrderType)
    {

    case 1:  //如果订单类型为任务.


    if($Serialno)
    { //判断任务流水号不为空

     $Tasks = M("task"); //调用模型
	 $Taskwhere['taskSerialno']=$Serialno;  //拼写where条件
	 $TaskData['PayStatus']=1; //更新支付状态为已经支付
	 $TaskData['taskStatus']=8; //更新任务状态为待发布
	 $TaskRs = $Tasks->where($Taskwhere)->save($TaskData); //更新数据
	 //print_r(M()->getLastSql());

    }

    if($TaskRs)
    {
     $task = D("Mob/Task");  //为了避免跨模块调用问题，所以增加模块
	return $task->releaseTask($Serialno);   //执行发布任务操作

    }

    break;

    case 2:  //其他的先预留，后续再根据需求实现。
    break;

	case 3:    //红包


    $activityId = $OrderInfo['businessId'];

    $activity =  D("Mob/Activity");
    $activitInfo = $activity->queryActivity($activityId);
    $redpactkId = $activitInfo['paySerialno'];
    $businessId = $activitInfo['businessId'];

    if(!$activitInfo)
    {
     return ;
    }
    if($activitInfo['status']==1) //已经支付过了。
    {
    return ;
    }

    $activity->releaseActivity($activityId,$activitInfo['sponsorUid']);



	break;




    case 4:    //企业付

    break;

    }
	}
	public function index ()
	{
	$this->setTitle('test');
	$this->display();
	}

}